#include <QResizeEvent>
#include <QScrollBar>
#include <QScrollArea>
#include "ThemeEditor.h"
#include "Include/ITheme.h"
#include "ui_ThemeEditor.h"
#include "LexerEdit.h"



ThemeEditor::ThemeEditor(ITheme *theme, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ThemeEditor),
    _theme(theme)
{
    ui->setupUi(this);
    connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onAccept()));
    connect(ui->lexersCmb, SIGNAL(currentIndexChanged(QString)), SLOT(lexersChange(QString)));

    _lexers = loadPlugin<Lexers::ILexers>("liblexers.so");

    ui->lexersCmb->addItems(_lexers->names());
    foreach(QString lexName, _lexers->names()){
        QScrollArea *area = new QScrollArea(this);
        LexerEdit *edit = new LexerEdit(_lexers->get(lexName, this), _theme, this);
        area->setWidget(edit);
        area->setWidgetResizable(true);
        _lexMap[lexName] = ui->stackedWidget->addWidget(area);
    }

    ui->backColor->setColor(_theme->background());
    ui->selBackColor->setColor(_theme->selectBackground());
    ui->selectColor->setColor(_theme->selectForeground());
    ui->marBackColor->setColor(_theme->marginBackground());
    ui->marColor->setColor(_theme->marginForeground());
    ui->marSelColor->setColor(_theme->marginSelectForeground());

    lexersChange(ui->lexersCmb->currentText());
}

ThemeEditor::~ThemeEditor()
{
    delete ui;
}

void ThemeEditor::lexersChange(const QString& name)
{
    ui->stackedWidget->setCurrentIndex(_lexMap[name]);
}

void ThemeEditor::onAccept()
{
    _theme->setBackground(ui->backColor->color());
    _theme->setSelectBackground(ui->selBackColor->color());
    _theme->setSelectForeground(ui->selectColor->color());
    _theme->setMarginBackground(ui->marBackColor->color());
    _theme->setMarginForeground(ui->marColor->color());
    _theme->setMarginSelectForeground(ui->marSelColor->color());

    for(int i = 0; i < ui->stackedWidget->count(); i++){
        QScrollArea *area = qobject_cast<QScrollArea*>(ui->stackedWidget->widget(i));
        LexerEdit *edt = qobject_cast<LexerEdit*>(area->widget());
        edt->save();
    }

    accept();
}

